package com.tjetc.service.impl;

import com.tjetc.domain.Order;
import com.tjetc.domain.OrderSettlement;
import com.tjetc.domain.Vehicle;
import com.tjetc.mapper.OrderSettlementMapper;
import com.tjetc.mapper.VehicleMapper;
import com.tjetc.service.OrderSettlementService;
import com.tjetc.utils.Db;
import com.tjetc.vo.Result;

import javax.xml.crypto.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

public class OrderSettlementServiceImpl implements OrderSettlementService {
    private static OrderSettlementMapper orderSettlementMapper=Db.getMapper(OrderSettlementMapper.class);
    private VehicleMapper vehicleMapper = Db.getMapper(VehicleMapper.class);
    private Result result=new Result();

    @Override
    public Result insert(OrderSettlement orderSettlement, Order order) {
        Vehicle vehicle = vehicleMapper.selectByPrimaryKey(order.getVehicleId());

        BigDecimal hour = new BigDecimal(24);
        BigDecimal cost = vehicle.getDailyRentalRate().divide(hour, 2);
        BigDecimal hours = new BigDecimal(ChronoUnit.HOURS.between(order.getRentalStartDate(),LocalDateTime.now()));
        orderSettlement.setFinalCost(hours.multiply(cost));
        BigDecimal result111=orderSettlement.getFinalCost().subtract(order.getTotalCost());
        int result222 = result111.compareTo(BigDecimal.ZERO);
        if (result222>0){
            orderSettlement.setAdditionalCharges(result111);
        }else {
            orderSettlement.setAdditionalCharges(BigDecimal.ZERO);
            orderSettlement.setFinalCost(order.getTotalCost());
        }
        int rows = orderSettlementMapper.insert(orderSettlement);
        if (rows==1){
            return result.setCode(200).setMsg("订单结算成功");
        }else {
            return result.setCode(500).setMsg("订单结算失败");
        }

    }

    @Override
    public OrderSettlement findByOrderId(String orderId) {
        return orderSettlementMapper.findByOrderId(orderId);
    }

    @Override
    public List<OrderSettlement> list(Integer customerId) {
        return orderSettlementMapper.list(customerId);
    }

    @Override
    public OrderSettlement findByOrderIdLink(String orderId) {
        return orderSettlementMapper.findByOrderIdLink(orderId);
    }

}
